package com.sk.weichat.ui.me;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.core.AVersionService;
import com.allenliu.versionchecklib.core.DownloadManager;
import com.allenliu.versionchecklib.utils.ALog;
import com.allenliu.versionchecklib.utils.AllenEventBusUtil;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.NotificationBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.allenliu.versionchecklib.v2.eventbus.AllenEventType;
import com.allenliu.versionchecklib.v2.net.RequestVersionManager;
import com.allenliu.versionchecklib.v2.ui.BuilderHelper;
import com.allenliu.versionchecklib.v2.ui.UIActivity;
import com.allenliu.versionchecklib.v2.ui.VersionService;
import com.sk.weichat.R;
import com.sk.weichat.bean.VersionInfo;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.mvp.contract.VersionContract;
import com.sk.weichat.mvp.presenter.VersionPresenter;
import com.sk.weichat.permission.Permission;
import com.sk.weichat.ui.WebAgreementActivity;
import com.sk.weichat.ui.account.LoginActivity;
import com.sk.weichat.ui.account.RegisterUserBasicInfoActivity;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.PermissionHelper;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.CustomVersionDialog;
import com.sk.weichat.view.SharePopupWindow;
import java.io.File;

import static com.allenliu.versionchecklib.utils.AppUtils.*;

public class AboutActivity extends BaseActivity implements View.OnClickListener , VersionContract {

    private Button btn_update;
    private TextView tv_download_progress;
    private TextView tv_privacy_policy;
    private TextView tv_user_agreement;
    private VersionInfo mVersionInfo;
    private DownloadBuilder builder;
    private boolean isDown = false;//判断是否正在下载

    private VersionPresenter mVersionPresenter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_about);
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText("关于悦聊");
        ImageView ivRight = findViewById(R.id.iv_title_right);
        ivRight.setImageResource(R.drawable.share);
        ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharePopupWindow mSharePopupWindow = new SharePopupWindow(AboutActivity.this);
                mSharePopupWindow.showAtLocation(findViewById(R.id.about), Gravity.BOTTOM, 0, 0);
            }
        });

        TextView versionTv = findViewById(R.id.version_tv);
        versionTv.setText( "v" + DeviceInfoUtil.getVersionName(mContext));

        btn_update  = findViewById(R.id.btn_update);
        btn_update.setOnClickListener(this);
        tv_download_progress = findViewById(R.id.tv_download_progress);

        tv_privacy_policy = findViewById(R.id.tv_privacy_policy);
        tv_user_agreement = findViewById(R.id.tv_user_agreement);
        tv_privacy_policy.setOnClickListener(this);
        tv_user_agreement.setOnClickListener(this);
        TextView tvCompany = findViewById(R.id.company_tv);
        TextView tvCopyright = findViewById(R.id.copy_right_tv);

        mVersionPresenter = new VersionPresenter(coreManager,this);
        mVersionInfo = new VersionInfo();
        mVersionPresenter.getVersionInfo();

        if (VersionService.builder!=null){
            isDown = true;
            VersionService.builder.setApkDownloadListener(new APKDownloadListener() {
                @Override
                public void onDownloading(int progress) {
                    isDown = true;
                    tv_download_progress.setVisibility(View.VISIBLE);
                    tv_download_progress.setText("正在下载"+progress+"%");
                }

                @Override
                public void onDownloadSuccess(File file) {
                    isDown = false;
                    tv_download_progress.setVisibility(View.GONE);
                }

                @Override
                public void onDownloadFail() {

                }
            });
        }else {
            isDown = false;
        }
    }

    private void initUpdata(){

        UIData uiData = UIData.create();
        uiData.setTitle("发现新版本");
        uiData.setDownloadUrl(mVersionInfo.getAppUrl());
        uiData.setContent(Html.fromHtml(mVersionInfo.getAppExplain()).toString());

        builder = AllenVersionChecker
                .getInstance()
                .downloadOnly(uiData);
        builder.setNewestVersionCode(mVersionInfo.getAppVersionCode());
        builder.setForceRedownload(false); //默认false 下载忽略本地缓存
        builder.setShowNotification(true); // 默认true 是否显示通知栏
        builder.setNotificationBuilder(createCustomNotification());
        builder.setCustomVersionDialogListener((context, versionBundle) -> {
            CustomVersionDialog dialog= new CustomVersionDialog(context,R.style.alert_dialog,R.layout.dialog_update_version);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            Window dialogWindow = dialog.getWindow();
            WindowManager m = getWindowManager();
            Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
            WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
            p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.8
            dialogWindow.setAttributes(p);
            TextView tv_version_code = dialog.findViewById(R.id.tv_version_code);
            tv_version_code.setText("V"+mVersionInfo.getAppVersion());
            //versionBundle 就是UIData，之前开发者传入的，在这里可以拿出UI数据并展示
            TextView textView = dialog.findViewById(R.id.tv_msg);
            textView.setText(versionBundle.getContent());
            ImageView versionchecklib_version_dialog_cancel = dialog.findViewById(R.id.versionchecklib_version_dialog_cancel);
            if (mVersionInfo.getAppStatus()==0){
                versionchecklib_version_dialog_cancel.setVisibility(View.VISIBLE);
            }else {
                versionchecklib_version_dialog_cancel.setVisibility(View.GONE);
            }
            return dialog;
        });
        if (mVersionInfo.getAppStatus()==1) {//强制更新，关闭界面
            builder.setShowDownloadingDialog(true);
            builder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                    finish();
                }
            });
        }
        builder.setApkDownloadListener(new APKDownloadListener() {
            @Override
            public void onDownloading(int progress) {
                isDown = true;
                tv_download_progress.setVisibility(View.VISIBLE);
                tv_download_progress.setText("正在下载"+progress+"%");
            }

            @Override
            public void onDownloadSuccess(File file) {
                isDown = false;
                tv_download_progress.setVisibility(View.GONE);
            }

            @Override
            public void onDownloadFail() {

            }
        });

        //设置是否显示下载对话框
        builder.setShowDownloadingDialog(false);
    }
    @Override
    public void onClick(View v) {
        if (v==btn_update){
            if (new PermissionHelper().RequestPermisson(AboutActivity.this, Permission.Group.STORAGE)) {
                if (!isDown){
                    final String downloadPath = getDownloadFilePath();
                    if (DownloadManager.checkAPKIsExists(getApplicationContext(), downloadPath, mVersionInfo.getAppVersionCode()) && !builder.isForceRedownload()) {
                        ALog.e("using cache");
                        install();
                        return;
                    }
                    builder.executeMission(AboutActivity.this);
                }else {
                    ToastUtil.showToast(this,"正在下载，请稍后...");
                }
            }

        }else if (v==tv_privacy_policy){
            goToWeb("悦聊隐私政策", coreManager.getConfig().GET_POLICY);
        }else if (v==tv_user_agreement){
            goToWeb("悦聊用户协议", coreManager.getConfig().GET_USER_AGREEMENT);
        }
    }
    /*自定义通知栏显示下载进度*/
    private NotificationBuilder createCustomNotification() {
        return NotificationBuilder.create()
                .setRingtone(true)
                .setIcon(R.mipmap.icon)
                .setTicker("custom_ticker")
                .setContentTitle("版本更新")
                .setContentText("%d%%");
    }

    private String getDownloadFilePath() {
        return builder.getDownloadAPKPath() + getString(R.string.versionchecklib_download_apkname, builder.getApkName() != null ? builder.getApkName() : getPackageName());
    }
    private void install() {
        BuilderHelper builderHelper = new BuilderHelper(getApplicationContext(), builder);
        AllenEventBusUtil.sendEventBus(AllenEventType.DOWNLOAD_COMPLETE);
        final String downloadPath = getDownloadFilePath();
        if (builder.isSilentDownload()) {
            showVersionDialog();
        } else {
            installApk(getApplicationContext(), new File(downloadPath), builder.getCustomInstallListener());
            builderHelper.checkForceUpdate();
        }
    }
    /**
     * 开启UI展示界面
     */
    private void showVersionDialog() {
        if (builder != null) {
            Intent intent = new Intent(this, UIActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    private void goToWeb(String title, String url) {
        Intent intent = new Intent(AboutActivity.this, WebAgreementActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("url", url);
        startActivity(intent);
    }

    @Override
    public void getVersionInfo(VersionInfo mInfo) {
        //判断版本号是否大于 本地版本  大于则更新
        if (mInfo.getAppVersionCode()>AppUtils.getLocalVersionCode(mContext)){
            mVersionInfo = mInfo;
            btn_update.setVisibility(View.VISIBLE);
            btn_update.setText("更新版本("+mInfo.getAppVersion()+")");
            initUpdata();
        }else {
            btn_update.setVisibility(View.GONE);
        }
    }
}
